import { Card, Table, Row, Col, Statistic, Tag, Progress, Space, Button, Typography, Tooltip, Input, Select } from '@/utils/antd-imports';
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined, SearchOutlined, FilterOutlined } from '@/utils/icons';
import React from 'react';













import DatePicker from 'antd/es/date-picker';


const { Text } = Typography;
const { Search } = Input;
const { Option } = Select;

// 计算持续时间（从开始日期到结束日期）
const calculateDuration = (startDate, endDate) => {
  if (!startDate || !endDate) return '-';
  try {
    const start = new Date(startDate);
    const end = new Date(endDate);
    const diffTime = Math.abs(end - start);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return Math.round(diffDays / 30); // 返回月数
  } catch (error) {
    return '-';
  }
};

// 默认分包项目数据
const defaultSubProjectsData = [
  {
    id: '1',
    serialNumber: '1',
    projectType: '分包项目',
    clientName: '华东医院',
    department: '外科',
    division: '神经外科',
    name: '神经外科手术器械采购项目',
    contactPerson: '张医生',
    contractNumber: 'HT20230001',
    currentPrice: 285000,
    contractAmount: 300000,
    budgetAmount: 280000,
    startDate: '2023-01-15',
    duration: 12,
    expectedEndDate: '2024-01-14',
    status: '已回款',
    progress: 100
  },
  {
    id: 'SP002',
    serialNumber: '2',
    projectType: '分包项目',
    clientName: '北方医院',
    department: '内科',
    division: '心血管内科',
    name: '心血管介入耗材供应项目',
    contactPerson: '李主任',
    contractNumber: 'HT20230002',
    currentPrice: 420000,
    contractAmount: 450000,
    budgetAmount: 400000,
    startDate: '2023-03-10',
    duration: 18,
    expectedEndDate: '2024-09-09',
    status: '验收中',
    progress: 60
  },
  {
    id: 'SP003',
    serialNumber: '3',
    projectType: '分包项目',
    clientName: '南方医疗中心',
    department: '检验科',
    division: '生化检验',
    name: '检验试剂年度供应项目',
    contactPerson: '王技师',
    contractNumber: 'HT20230003',
    currentPrice: 185000,
    contractAmount: 200000,
    budgetAmount: 190000,
    startDate: '2023-05-20',
    duration: 12,
    expectedEndDate: '2024-05-19',
    status: '开票中',
    progress: 80
  },
  {
    id: 'SP004',
    serialNumber: '4',
    projectType: '分包项目',
    clientName: '西部医院',
    department: '影像科',
    division: '放射科',
    name: '放射科设备维护服务',
    contactPerson: '赵主任',
    contractNumber: 'HT20230004',
    currentPrice: 150000,
    contractAmount: 180000,
    budgetAmount: 160000,
    startDate: '2023-07-01',
    duration: 24,
    expectedEndDate: '2025-06-30',
    status: '待回款',
    progress: 90
  },
  {
    id: 'SP005',
    serialNumber: '5',
    projectType: '分包项目',
    clientName: '中心医院',
    department: '急诊科',
    division: '急诊内科',
    name: '急诊急救耗材供应',
    contactPerson: '周护士长',
    contractNumber: 'HT20230005',
    currentPrice: 98000,
    contractAmount: 120000,
    budgetAmount: 100000,
    startDate: '2023-09-15',
    duration: 6,
    expectedEndDate: '2024-03-14',
    status: '未验收',
    progress: 30
  }
];

export const SubcontractTab = ({ subProjectsData = defaultSubProjectsData }) => {
  // 转换后端数据格式，适配表格显示
  const transformedData = React.useMemo(() => {
    if (!subProjectsData || subProjectsData.length === 0) return [];
    
    // 检查是否为后端数据格式（有 projectSubname 字段）
    const isBackendData = subProjectsData[0]?.projectSubname !== undefined;
    
    if (isBackendData) {
      // 后端数据格式转换
      return subProjectsData.map((item, index) => ({
        id: item.id,
        serialNumber: index + 1,
        projectType: item.projectTypeName || '分包项目',
        clientName: item.customerName || '-',
        department: item.department || '-',
        division: item.division || '-',
        name: item.projectSubname || item.projectName || '-',
        contactPerson: item.contactPerson || '-',
        contractNumber: item.projectCode || '-',
        currentPrice: item.currentPrice || 0,
        contractAmount: item.estimatedCost || 0,
        budgetAmount: item.projectBudget || 0,
        startDate: item.startDate || '-',
        duration: item.duration || calculateDuration(item.startDate, item.endDate),
        expectedEndDate: item.endDate || '-',
        status: item.status || '-',
        progress: item.progress || 0,
        // 保留原始数据以便后续使用
        originalData: item
      }));
    }
    
    // 默认格式，直接使用
    return subProjectsData.filter(p => p.projectType === '分包项目');
  }, [subProjectsData]);
  
  const [filteredData, setFilteredData] = React.useState(transformedData);
  const [searchText, setSearchText] = React.useState('');
  const [statusFilter, setStatusFilter] = React.useState(null);
  const [departmentFilter, setDepartmentFilter] = React.useState(null);
  
  // 当 transformedData 变化时更新 filteredData
  React.useEffect(() => {
    setFilteredData(transformedData);
  }, [transformedData]);

  // 计算分包页签的统计数据
  const calculateSubcontractStats = () => {
    const total = filteredData.length;
    const totalContractAmount = filteredData.reduce((sum, p) => sum + p.contractAmount, 0);
    const totalBudgetAmount = filteredData.reduce((sum, p) => sum + p.budgetAmount, 0);
    
    return {
      total,
      totalContractAmount,
      totalBudgetAmount
    };
  };

  // 处理搜索和筛选
  const handleSearch = () => {
    let result = transformedData;
    
    if (searchText) {
      result = result.filter(item =>
        item.clientName.includes(searchText) ||
        item.name.includes(searchText) ||
        item.contractNumber.includes(searchText) ||
        item.contactPerson.includes(searchText)
      );
    }
    
    if (statusFilter) {
      result = result.filter(item => item.status === statusFilter);
    }
    
    if (departmentFilter) {
      result = result.filter(item => item.department === departmentFilter);
    }
    
    setFilteredData(result);
  };

  // 重置筛选
  const resetFilters = () => {
    setSearchText('');
    setStatusFilter(null);
    setDepartmentFilter(null);
    setFilteredData(transformedData);
  };

  const subcontractStats = calculateSubcontractStats();

  // 根据状态获取标签颜色
  const getStatusColor = (status) => {
    const colors = {
      '未验收': 'default',
      '验收中': 'blue',
      '开票中': 'orange',
      '待回款': 'purple',
      '已回款': 'green'
    };
    return colors[status] || 'default';
  };

  // 获取所有部门和状态选项
  const getFilterOptions = () => {
    const departments = [...new Set(transformedData.map(p => p.department))];
    const statuses = [...new Set(transformedData.map(p => p.status))];
    
    return { departments, statuses };
  };

  const { departments, statuses } = getFilterOptions();

  // 子项目表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: 60,
      fixed: 'left'
    },
    {
      title: '客户名称',
      dataIndex: 'clientName',
      key: 'clientName',
      width: 150,
      fixed: 'left'
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 120
    },
    {
      title: '科室',
      dataIndex: 'division',
      key: 'division',
      width: 120
    },
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      fixed: 'left',
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '对接人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      width: 100
    },
    {
      title: '合同号/呈批号',
      dataIndex: 'contractNumber',
      key: 'contractNumber',
      width: 150,
      render: (text) => <Text code>{text}</Text>
    },
    {
      title: '时价(元)',
      dataIndex: 'currentPrice',
      key: 'currentPrice',
      width: 120,
      render: (price) => (
        <Text>{price ? price.toLocaleString() : '-'}</Text>
      )
    },
    {
      title: '合同/订单金额(元)',
      dataIndex: 'contractAmount',
      key: 'contractAmount',
      width: 150,
      render: (amount) => (
        <Text strong>{amount.toLocaleString()}</Text>
      )
    },
    {
      title: '预算金额(元)',
      dataIndex: 'budgetAmount',
      key: 'budgetAmount',
      width: 150,
      render: (amount) => (
        <Text>{amount.toLocaleString()}</Text>
      )
    },
    {
      title: '订单开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '时长(月)',
      dataIndex: 'duration',
      key: 'duration',
      width: 100
    },
    {
      title: '预计结束时间',
      dataIndex: 'expectedEndDate',
      key: 'expectedEndDate',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      fixed: 'right',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {status}
        </Tag>
      )
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      width: 150,
      render: (progress) => (
        <Progress percent={progress} size="small" />
      )
    }
  ];

  return (
    <>
      <div style={{ overflowX: 'auto', marginBottom: 24 }}>
        <div style={{ display: 'flex', minWidth: 'max-content' }}>
          <div style={{ minWidth: '180px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="分包项目数" 
                value={subcontractStats.total} 
                precision={0}
                valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '200px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="合同总金额(元)" 
                value={subcontractStats.totalContractAmount} 
                precision={0}
                valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '200px' }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="预算总金额(元)" 
                value={subcontractStats.totalBudgetAmount} 
                precision={0}
                valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
        </div>
      </div>
      
      <Card 
        title="分包项目管理" 
        extra={
          <Space>
            <Button icon={<FilterOutlined />} onClick={resetFilters}>
              重置筛选
            </Button>
          </Space>
        }
        style={{ marginBottom: 16 }}
      >
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Search
              placeholder="搜索客户/项目/合同号/对接人"
              allowClear
              enterButton={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={handleSearch}
            />
          </Col>
          <Col span={6}>
            <Select
              placeholder="按部门筛选"
              style={{ width: '100%' }}
              allowClear
              value={departmentFilter}
              onChange={value => setDepartmentFilter(value)}
              onBlur={handleSearch}
            >
              {departments.map(dept => (
                <Option key={dept} value={dept}>{dept}</Option>
              ))}
            </Select>
          </Col>
          <Col span={6}>
            <Select
              placeholder="按状态筛选"
              style={{ width: '100%' }}
              allowClear
              value={statusFilter}
              onChange={value => setStatusFilter(value)}
              onBlur={handleSearch}
            >
              {statuses.map(status => (
                <Option key={status} value={status}>{status}</Option>
              ))}
            </Select>
          </Col>
          <Col span={4}>
            <Button type="primary" onClick={handleSearch} block>
              筛选
            </Button>
          </Col>
        </Row>
      </Card>
      
      <Table
        columns={columns}
        dataSource={filteredData}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        scroll={{ x: 1800 }}
        bordered
        size="middle"
      />
    </>
  );
};